// 此文件为自定义v-指令文件

// 拖拽左右宽度
const resizeDomX = {
  bind(el, binding) {
    let startX, startWidth;
    const afterPseudoElement = document.createElement('div');
    afterPseudoElement.className = 'resize-handle';
    el.appendChild(afterPseudoElement);

    // 设置父元素的position为relative
    el.style.position = 'relative';

    function onMouseDown(event) {
      startX = event.pageX;
      startWidth = parseInt(document.defaultView.getComputedStyle(el).width, 10);
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    }

    function onMouseMove(event) {
      const width = startWidth + (event.pageX - startX);
      el.style.width = `${width}px`;
    }

    function onMouseUp() {
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
      // Emit event on resize
      if (binding.value && typeof binding.value === 'function') {
        binding.value({
          width: parseInt(document.defaultView.getComputedStyle(el).width, 10)
        });
      }
    }

    afterPseudoElement.addEventListener('mousedown', onMouseDown);

    // 设置.resize-handle类的样式
    afterPseudoElement.style.position = 'absolute';
    afterPseudoElement.style.top = '0';

    afterPseudoElement.style.height = '100%';
    afterPseudoElement.style.width = '1px';
    afterPseudoElement.style.backgroundColor = '#ccc'; // 设置伪元素的背景颜色
    afterPseudoElement.style.cursor = 'ew-resize'; // 改变鼠标样式
    if (binding.value === 'left') {
      afterPseudoElement.style.left = '0';
    } else {
      afterPseudoElement.style.right = '0';
    }
  }
};

const directives = {
  resizeDomX
};
// 这种写法可以批量注册指令
export default {
  install(Vue) {
    Object.keys(directives).forEach(key => {
      Vue.directive(key, directives[key]);
    });
  }
};
